use adw::prelude::*;
use gtk::glib;

use crate::ui::chat_record_item::RecordItem;
use crate::ui::chat_record_list::ChatRecordListView;

pub mod ui;

const APP_ID: &str = "org.astral_sphere.Sleepwalker";

fn main() -> Result<(), anyhow::Error> {
    // env_logger::init();
    colog::init();

    let application = adw::Application::builder().application_id(APP_ID).build();

    application.connect_activate(|app| {
        // Load CSS stylesheet after GTK is initialized
        load_css();
        build_ui(app);
    });

    let exit_code = application.run();

    let code = exit_code.get();
    if code != 0 {
        Err(anyhow::anyhow!(
            "Application exited with error code {}",
            code
        ))
    } else {
        Ok(())
    }
}

fn load_css() {
    let provider = gtk::CssProvider::new();
    provider.load_from_string(include_str!("../src/ui/style.css"));

    gtk::style_context_add_provider_for_display(
        &gtk::gdk::Display::default().expect("Could not connect to a display."),
        &provider,
        gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
    );
}

fn build_ui(application: &adw::Application) {
    let window = adw::ApplicationWindow::builder()
        .application(application)
        .title("Sleepwalker")
        .build();
    window.set_default_size(1000, 600);

    // Split the window into to parts with NavigationSplitView
    let navigation = adw::NavigationSplitView::new();
    navigation.add_css_class("animated-navigation");
    // Set show_content to true to ensure sidebar is the one being collapsed
    // When show_content is true, collapsing hides the sidebar and shows the back button
    // When show_content is false, collapsing hides the content area
    navigation.set_show_content(true);
    window.set_content(Some(&navigation));

    // left page
    let left_header_bar = adw::HeaderBar::new();
    left_header_bar.set_title_widget(Some(&adw::WindowTitle::new("Sleepwalker", "v0.1")));

    // 使用 ChatRecordListView 替代 SleepwalkerListView
    let chat_list_view = ChatRecordListView::new();

    // // 添加一些示例项目
    // let item1 = RecordItem::new("对话记录 1");
    // let item2 = RecordItem::new("对话记录 2");
    // let item3 = RecordItem::new("对话记录 3");
    // let item4 = RecordItem::new("对话记录 4");
    // let item5 = RecordItem::new("对话记录 5");

    // chat_list_view.append(&item1);
    // chat_list_view.append(&item2);
    // chat_list_view.append(&item3);
    // chat_list_view.append(&item4);
    // chat_list_view.append(&item5);
    //
    for i in 1..=1000 {
        let item = RecordItem::new(format!("对话记录 {}", i));
        chat_list_view.append(&item);
    }

    let left_content = adw::ToolbarView::new();
    left_content.add_top_bar(&left_header_bar);
    left_content.set_content(Some(&chat_list_view));

    let left_page = adw::NavigationPage::builder()
        .title("Left")
        .child(&left_content)
        .can_pop(false) // Prevent showing back button in sidebar
        .build();

    // right page
    let right_header_bar = adw::HeaderBar::new();

    // Add button to the left side of the header bar
    let side_bar_is_collapsed = navigation.is_collapsed();
    let left_button = gtk::Button::builder()
        .icon_name(if side_bar_is_collapsed {
            "go-next-symbolic"
        } else {
            "go-previous-symbolic"
        })
        .tooltip_text(if side_bar_is_collapsed {
            "Expand sidebar"
        } else {
            "Collapse sidebar"
        })
        .build();
    left_button.connect_clicked(glib::clone!(
        #[weak]
        navigation,
        move |button| {
            if navigation.is_collapsed() {
                navigation.set_collapsed(false);
                button.set_icon_name("go-previous-symbolic");
                button.set_tooltip_text(Some("Collapse sidebar"));
            } else {
                navigation.set_collapsed(true);
                button.set_icon_name("go-next-symbolic");
                button.set_tooltip_text(Some("Expand sidebar"));
            }
        }
    ));
    right_header_bar.pack_start(&left_button);

    let model_dropdown = gtk::DropDown::from_strings(&[
        "str1",
        "str22",
        "str333",
        "str4444",
        "str55555",
        "str666666",
        "str7777777",
    ]);
    model_dropdown.set_hexpand(true);
    right_header_bar.set_title_widget(Some(&model_dropdown));

    let right_content = adw::ToolbarView::new();
    right_content.add_top_bar(&right_header_bar);
    right_content.set_content(Some(&gtk::Label::new(Some("Hello world!"))));

    let right_page = adw::NavigationPage::builder()
        .title("Right")
        .child(&right_content)
        .can_pop(false) // Prevent showing back button in content
        .build();

    // Set the pages in the navigation split view
    navigation.set_sidebar(Some(&left_page));
    navigation.set_content(Some(&right_page));

    window.present();
}
